<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图书添加案例</title>
    <style type="text/css">
      .grid {
        margin: auto;
        width: 530px;
        text-align: center;
      }
      .grid table {
        border-top: 1px solid #c2d89a;
        width: 100%;
        border-collapse: collapse;
      }
      .grid th,
      td {
        padding: 10;
        border: 1px dashed #f3dcab;
        height: 35px;
        line-height: 35px;
      }
      .grid th {
        background-color: #f3dcab;
      }
      .grid .book {
        padding-bottom: 10px;
        padding-top: 5px;
        background-color: #f3dcab;
      }
      .grid .total {
        height: 30px;
        line-height: 30px;
        background-color: #f3dcab;
        border-top: 1px solid #c2d89a;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="grid">
        <div>
          <h1>图书管理</h1>
          <div class="book">
            <div>
              <label for="id">
                编号：
              </label>
              <input type="text" v-model.trim="id" :disabled="disabled" />
              <label for="name">
                名称：
              </label>
              <input type="text" id="name" v-model.trim="name" />
              <button @click.prevent="submit" :disabled="submitDisabled">
                提交
              </button>
            </div>
          </div>
        </div>
        <div class="total">
          <span>图书总数：</span>
          <span>{{total}}</span>
        </div>
        <table>
          <thead>
            <tr>
              <th>编号</th>
              <th>名称</th>
              <th>时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr :key="item.id" v-for="(item,index) in books">
              <td>{{item.id}}</td>
              <td>{{item.name}}</td>
              <td>{{item.date|form('yyyy-MM-hh')}}</td>
              <td>
                <a href="" @click.prevent="edit(item.id)">修改</a>
                <span>|</span>
                <a href="" @click.prevent="del(item.id)">删除</a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script>
      //时间过滤器
      Vue.filter('form', function (data, params) {
        /**
         * 对日期进行格式化，
         * @param date 要格式化的日期
         * @param format 进行格式化的模式字符串
         *     支持的模式字母有：
         *     y:年,
         *     M:年中的月份(1-12),
         *     d:月份中的天(1-31),
         *     h:小时(0-23),
         *     m:分(0-59),
         *     s:秒(0-59),
         *     S:毫秒(0-999),
         *     q:季度(1-4)
         * @return String
         * @author yanis.wang
         * @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
         */
        function dateFormat(date, format) {
          if (typeof date === 'string') {
            var mts = date.match(/(\/Date\((\d+)\)\/)/)
            if (mts && mts.length >= 3) {
              date = parseInt(mts[2])
            }
          }
          date = new Date(date)
          if (!date || date.toUTCString() == 'Invalid Date') {
            return ''
          }
          var map = {
            M: date.getMonth() + 1, //月份
            d: date.getDate(), //日
            h: date.getHours(), //小时
            m: date.getMinutes(), //分
            s: date.getSeconds(), //秒
            q: Math.floor((date.getMonth() + 3) / 3), //季度
            S: date.getMilliseconds(), //毫秒
          }

          format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
            var v = map[t]
            if (v !== undefined) {
              if (all.length > 1) {
                v = '0' + v
                v = v.substr(v.length - 2)
              }
              return v
            } else if (t === 'y') {
              return (date.getFullYear() + '').substr(4 - all.length)
            }
            return all
          })
          return format
        }
        // DateFormat(data, params)
        return dateFormat(data, params)
      })

      new Vue({
        el: '#app',

        data: {
          submitDisabled: false,
          disabled: false,
          sum: '',
          id: '',
          name: '',
          books: [
            { id: '1', name: '娃哈哈', date: '2018-9-10 10:20:10' },
            { id: '2', name: '阿弥陀佛么么哒', date: '2018-9-10 12:20:10' },
            { id: '3', name: '打豆豆', date: '2018-9-10 00:20:10' },
            { id: '4', name: '饮水机', date: '2018-9-10 08:20:10' },
          ],
        },

        methods: {
          //提交按钮
          submit() {
            this.disabled = false //id框的恢复

            var book = {
              // 获取表单数据
              id: this.id,
              name: this.name,
              date: new Date(),
            }

            if (
              //判断是否存在一样的id
              this.books.some((item) => {
                return this.id == item.id
              })
            ) {
              // 如果存在就是更新动作

              const count = this.id
              this.books.some((item) => {
                if (item.id == count) {
                  item.name = this.name
                }
              })
            } else {
              //   如果没有一样的id就是添加
              this.name.trim().length > 0
                ? this.books.push(book)
                : alert('名字不能为空')
            }
            this.id = this.name = ''
          },
          //修改按钮
          edit(id) {
            //id框的禁用
            this.disabled = true
            this.books.some((item) => {
              if (id == item.id) {
                this.id = item.id
                this.name = item.name
                return true
              }
            })
          },
          del(id) {
            let index = this.books.findIndex((item) => {
              return item.id == id
            })
            this.books.splice(index, 1)
          },
        },

        computed: {
          total() {
            return (this.all = parseInt(this.books.length))
          },
        },

        watch: {
          name(newName) {
            this.submitDisabled = this.books.some((item) => {
              if (item.name === this.name) {
                alert('name重父')
                return true
              }
            })
          },
        },
      })
    </script>
  </body>
</html>
